package com.yhd.rabbit.delay;

import com.rabbitmq.client.Channel;
import com.yhd.rabbit.config.DelayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * @author 二十
 * @since 2022/1/14 10:31 下午
 */
@Slf4j
@Component
public class DelayQueueMQ {


    @Resource
    private AmqpTemplate amqpTemplate;

    /**
     * 发送消息
     */
    public void sendMessage() {
        amqpTemplate.convertAndSend(
                DelayConfig.EXCHANGE_DIRECT_ORDER_CANCEL, DelayConfig.ROUTING_ORDER_CANCEL,
                "try send message to delay queue !",
                msg -> {
                    msg.getMessageProperties().setDelay(DelayConfig.DELAY_TIME * 1000);
                    return msg;
                });
        log.warn("消息发送成功！");

    }

    /**
     * 接收消息
     */
    @RabbitListener(queues = DelayConfig.QUEUE_ORDER_CANCEL)
    public void receiveMessages(String msg, Message message, Channel channel) throws Exception {
        log.warn("msg = " + msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
